<template>
  <div>
    <div>用户名: {{ user.username }}</div>
    <div>性别: {{ user.gender === 1 ? '女' : '男' }}</div>
    <div>学校: {{ user.school }}</div>
    <div>年龄: {{ user.age }}</div>
    <div>昵称: {{ user.nickname }}</div>
    <div>
      密码: ******
      <el-button
        size="mini"
        @click="openDialog"
      >
        修改密码
      </el-button>
    </div>
    <el-dialog
      title="修改密码"
      :visible="dialogFormVisible"
    >
      <el-form
        ref="passwordForm"
        :model="form"
        :rules="rules"
      >
        <el-form-item label="旧密码">
          <el-input v-model="form.oldPassword" />
        </el-form-item>

        <el-form-item label="新密码">
          <el-input v-model="form.newPassword" />
        </el-form-item>

        <el-form-item
          label="再次输入新密码"
          prop="rePassword"
        >
          <el-input v-model="form.rePassword" />
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="submitForm"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex';

export default {
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.form.newPassword !== value) {
          callback(new Error('两次密码不一致'));
        }
        callback();
      }
    };
    return {
      dialogFormVisible: false,
      form: {
        oldPassword: '',
        newPassword: '',
        rePassword: '',
      },
      rules: {
        rePassword: [{ validator: validatePass, trigger: 'blur' }],
      },
    };
  },
  computed: {
    ...mapState({
      user: (state) => state.user.user,
    }),
  },
  methods: {
    openDialog() {
      this.dialogFormVisible = true;
    },
    submitForm() {
      this.$refs.passwordForm.validate(async (valid) => {
        if (valid) {
          try {
            await this.$request({
              url: '/api/user/changePassword',
              method: 'put',
              data: {
                newPassword: this.form.newPassword,
                oldPassword: this.form.oldPassword,
              },
            });
            this.$message({
              message: '恭喜你,修改密码成功',
              type: 'success',
            });
            this.dialogFormVisible = false;
          } catch (error) {
            this.$message.error('修改密码失败');
          }
        } else {
          return false;
        }
        return null;
      });
    },
  },
};
</script>

<style>
</style>
